﻿using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using Mall.Model;
using Serialize.Library;
using System;
using System.Collections.Generic;
using System.Text;

namespace Mall.Logic
{
    /// <summary>
    /// 移动端用户操作逻辑类
    /// </summary>
    public class ClientInfoServiceImpl : OperationLogicImpl, IClientInfoService
    {

        #region PC管理端逻辑

        #region 查询
        /// <summary>
        ///根据关键字分页获取列表
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<ClientInfoResponse>> LoadPageList(ParametersInfo<string> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<ClientInfoResponse>>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                int isDeleted = (int)IsDeleted.Deleted;
                var result = con.QuerySet<ClientInfoEntity>().Where(a => a.is_deleted != isDeleted);
                if (inputInfo.parameters.IsNotNullOrEmpty())
                {
                    result.Where(p => p.name.Equals(inputInfo.parameters)
                      ||p.mobile_phone.Equals(inputInfo.parameters)
                      ||p.nickname.Equals(inputInfo.parameters)
                      ||p.open_id.Equals(inputInfo.parameters)
                    );
                }

                #region 排序
                if (inputInfo.field.IsNullOrEmpty())
                {
                    inputInfo.field = " name";
                }
                if (inputInfo.order.IsNullOrEmpty())
                {
                    inputInfo.order = " asc";
                }
                if (inputInfo.order.ToLower() == "asc")
                {
                    result.OrderBy(inputInfo.field);
                }
                else
                {
                    result.OrderByDescing(inputInfo.field);
                }
                #endregion

                var queryInfo = result.PageList(inputInfo.page, inputInfo.limit);
                if (queryInfo.Items.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = queryInfo.Items.MapToList<ClientInfoResponse>();
                    resultInfo.Count = queryInfo.Total;
                    resultInfo.Msg = "获取成功！";
                }
                else
                {
                    resultInfo.Msg = "无对应值存在！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 更新

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> SaveInfo(ClientInfoModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                var result = 0;
                if (inputInfo.id.IsNotNullOrEmpty())
                {
                    #region Modify
                    var modifyInfo = con.QuerySet<ClientInfoEntity>().Where(p => p.id == inputInfo.id).Get();
                    if (modifyInfo != null)
                    {
                        modifyInfo.name = inputInfo.name;
                        modifyInfo.mobile_phone = inputInfo.mobile_phone;
                        modifyInfo.sex = inputInfo.sex;
                        modifyInfo.is_valid = inputInfo.is_valid;
                        modifyInfo.integral = inputInfo.integral;
                        modifyInfo.monetary = inputInfo.monetary;
                        modifyInfo.remarks = inputInfo.remarks;

                        result = con.CommandSet<ClientInfoEntity>().Update(modifyInfo);
                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "修改成功！";
                            AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.ClientInfoManage, $"修改客户信息，修改信息：{ JsonHelper.ToJson(inputInfo)}");
                        }
                        else
                        {
                            resultInfo.Code = ActionCodes.InvalidOperation;
                            resultInfo.Msg = "修改失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Code = ActionCodes.InvalidOperation;
                        resultInfo.Msg = "对应Id的信息不存在！";
                    }
                    #endregion
                }
                else
                {
                    #region Add
                    var addInfo = inputInfo.MapTo<ClientInfoEntity>();
                    addInfo.id = GuidHelper.GetGuid();
                    addInfo.create_time = DateTime.Now;
                    result = con.CommandSet<ClientInfoEntity>().Insert(addInfo);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "添加成功！";
                        AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.ClientInfoManage, $"添加了一个客户信息，新增信息：{ JsonHelper.ToJson(inputInfo)}");
                    }
                    else
                    {
                        resultInfo.Code = ActionCodes.InvalidOperation;
                        resultInfo.Msg = "添加失败！";
                    }
                    #endregion
                }
            }
            return resultInfo;
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除XXX信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> ids)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //删除
                con.Transaction(tran => {

                    var info = tran.QuerySet<ClientInfoEntity>().Where(p => p.id.In(ids.ToArray())).ToList();
                    info.ForEach(a => a.is_deleted = (int)IsDeleted.Deleted);
                    var result = tran.CommandSet<ClientInfoEntity>().Update(info);
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "删除成功！";
                        AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.ClientInfoManage, $"删除客户信息成功，逻辑删除信息：{ JsonHelper.ToJson(ids)}");
                    }
                    else
                    {
                        resultInfo.Msg = "删除失败！";
                    }
                }); 
            }
            return resultInfo;
        }
        #endregion

        #endregion

        #region 移动端逻辑
        /// <summary>
        /// 微信自动授权登录
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<WechatUserLoginInfo> LoginCheck(ClientLoginRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<WechatUserLoginInfo>();
            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //先查询是否有该账号存在
                var clientInfo = con.QuerySet<ClientInfoEntity>().Where(p => p.open_id == inputInfo.open_id).Get();

                if (clientInfo != null)
                {
                    if (clientInfo.is_valid == (int)IsValid.Valid)
                    {
                        clientInfo.country = inputInfo.country;
                        clientInfo.province = inputInfo.province;
                        clientInfo.city = inputInfo.city;
                        clientInfo.head_img = inputInfo.head_img;
                        clientInfo.nickname = inputInfo.nickname;
                        clientInfo.sex = inputInfo.sex;
                        var modyResult = con.CommandSet<ClientInfoEntity>().Update(clientInfo);

                        var ticket = clientInfo.MapTo<WechatUserLoginInfo>();
                        string refreshToken = Guid.NewGuid().ToString();
                        SysUserServiceRedis<WechatUserLoginInfo>.SaveUserInfo(refreshToken, ticket, () =>
                        {
                            ticket.token = refreshToken;
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "操作成功";
                            resultInfo.Data = ticket;
                            AddOperationLog(OperationLogType.LoginOperation, BusinessTitleType.MallClientManage, $"登录成功！", clientInfo.id);
                        },
                        () =>
                        {
                            resultInfo.Msg = "缓存用户信息失败！";
                            resultInfo.Code = ActionCodes.CacheFailure;
                        });
                    }
                    else
                    {
                        resultInfo.Msg = "用户已被冻结，请与管理员联系！";
                        resultInfo.Code = ActionCodes.InvalidOperation;
                    }
                }
                else
                {
                    var clientInfoAdd= inputInfo.MapTo<ClientInfoEntity>();
                    clientInfoAdd.id = GuidHelper.GetGuid();
                    clientInfoAdd.is_valid = (int)IsValid.Valid;
                    clientInfoAdd.is_deleted= (int)IsDeleted.NotDeleted;
                    clientInfoAdd.create_time = DateTime.Now;
                    var result = con.CommandSet<ClientInfoEntity>().Insert(clientInfoAdd);
                    if (result > 0)
                    {
                        var ticket = clientInfoAdd.MapTo<WechatUserLoginInfo>();
                        string refreshToken = Guid.NewGuid().ToString();
                        SysUserServiceRedis<WechatUserLoginInfo>.SaveUserInfo(refreshToken, ticket, () =>
                        {
                            ticket.token = refreshToken;
                            resultInfo.Data = ticket;
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Msg = "登录成功！";
                            AddOperationLog(OperationLogType.AddOperation, BusinessTitleType.MallClientManage, $"登录成功,新增用户信息：{JsonHelper.ToJson(clientInfoAdd)}");
                        },
                        () =>
                        {
                            resultInfo.Msg = "缓存用户信息失败！";
                            resultInfo.Code = ActionCodes.CacheFailure;
                        });
                    }
                    else
                    {
                        resultInfo.Msg = "添加失败！";
                    }
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 通过微信openId获取用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public ResultJsonInfo<WechatUserLoginInfo> LoadByOpenId(string openId) {

            var resultInfo = new ResultJsonInfo<WechatUserLoginInfo>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //先查询是否有该账号存在
                var clientInfo = con.QuerySet<ClientInfoEntity>().Where(p => p.open_id == openId).Get();

                if (clientInfo != null)
                {
                    if (clientInfo.is_valid== (int)IsValid.Valid)
                    {
                        var ticket = clientInfo.MapTo<WechatUserLoginInfo>();
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "获取成功";
                        resultInfo.Data = ticket;
                    }
                    else
                    {
                        resultInfo.Msg = "用户已被冻结，请与管理员联系！";
                        resultInfo.Code = ActionCodes.InvalidOperation;
                    }
                }
                else
                {
                    resultInfo.Msg = "账号不存在！";
                    resultInfo.Code = ActionCodes.ObjectNotFound;
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 微信通过Id获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<WechatUserLoginInfo> LoadSingleById(string id) {

            var resultInfo = new ResultJsonInfo<WechatUserLoginInfo>();

            using (var con = DataBase.GetConnection(DatabaseName.Sql_BUS_DB.ToString()))
            {
                //先查询是否有该账号存在
                var clientInfo = con.QuerySet<ClientInfoEntity>().Where(p => p.id == id).Get();

                if (clientInfo != null)
                {
                    var ticket = clientInfo.MapTo<WechatUserLoginInfo>();
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "获取成功";
                    resultInfo.Data = ticket;
                }
                else
                {
                    resultInfo.Msg = "账号不存在！";
                    resultInfo.Code = ActionCodes.ObjectNotFound;
                }
            }
            return resultInfo;
        }

        #endregion
    }
}
